package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description MemberInterceptor
 * @Author songyu
 * @Date 2025-02-25  10:29
 */
@Slf4j
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截小程序用户校验token...");
        //1.拦截控制器方法的请求，如果不是控制器方法直接放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //2.获取请求的authorization,如果没有数据，设置返回401,抛异常“认证失败”
        String token = request.getHeader("authorization");
        if(StrUtil.isEmpty(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new RuntimeException("认证失败");
        }

        //3.解析token，获取载荷，载荷为空，设置返回401,抛异常“认证失败”
        Claims claims = tokenService.parseToken(token);
        if(ObjectUtil.isEmpty(claims)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new RuntimeException("认证失败");
        }

        //4.获取载荷中的userId,如果为空，设置返回401,抛异常“认证失败”
        Object userIdObj = claims.get("userId");
        Long userId = null;
        if(ObjectUtil.isEmpty(userIdObj)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new RuntimeException("认证失败");
        }
        userId = Long.valueOf(userIdObj.toString());

        //5.将有效的userId写入ThreadLocal
        UserThreadLocal.set(userId);

        //6.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal
        UserThreadLocal.remove();
    }
}